﻿create procedure dbo.UsePreferredMenu
(
		@PreferredTakeoutMenuID int,
		@TakeoutProviderID int,
		@TakeoutUserID int = null OUTPUT
	)
AS

BEGIN TRANSACTION	
	/* Create Temp table to build CSV */
	
	CREATE TABLE #PreferredTakeoutMenuCreator (InjectItem  varchar(20))
			
	INSERT INTO #PreferredTakeoutMenuCreator
	SELECT     CAST(dbo.PreferredTakeoutMenuItems.MenuItemID AS varchar) + ',' + CAST(dbo.PreferredTakeoutMenuItems.Quantity AS varchar) 
	                      AS InjectItems
	FROM         dbo.PreferredTakeoutMenu INNER JOIN
	                      dbo.PreferredTakeoutMenuItems ON dbo.PreferredTakeoutMenu.Id = dbo.PreferredTakeoutMenuItems.PreferredTakeoutMenuId
	WHERE     (dbo.PreferredTakeoutMenu.Id = @PreferredTakeoutMenuID)
	
	
	DECLARE @csvOutput varchar(8000)
	DECLARE @useQuotes bit 
	DECLARE @Instructions varchar(2000)
	DECLARE @UserID int
	
	set @useQuotes = 0
	
	SET @Instructions = (SELECT Instructions FROM dbo.PreferredTakeoutMenu WHERE Id = @PreferredTakeoutMenuID)
	SET @UserID = (SELECT UserID FROM PreferredTakeoutMenu WHERE Id = @PreferredTakeoutMenuID)
		
	exec dbo.sp_MakeCharList 'select InjectItem from #PreferredTakeoutMenuCreator', @csvOutput OUTPUT, @useQuotes
	
	exec dbo.CreateTakeoutUser @TakeoutProviderID, @UserID, @Instructions, @csvOutput, @TakeoutUserID OUTPUT

If @@error = 0
	COMMIT TRANSACTION
ELSE
	ROLLBACK TRANSACTION
	
	
	RETURN


